package com.example.itshome.network;

import android.app.Activity;
import com.example.itshome.adapter.CircleListPageRecycleViewAdapter;
import com.example.itshome.entity.CircleEntity;
import com.example.itshome.entity.MyInteger;
import com.example.itshome.manager.UserInfoManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class GetCirclePostRequest extends AbstractRecycleVIewGetRequest<CircleEntity>{

    private MyInteger pageIndex;

    public GetCirclePostRequest setPageIndex(MyInteger pageIndex) {
        this.pageIndex = pageIndex;
        return this;
    }

    public GetCirclePostRequest(Activity activity) {
        super(activity);
    }

    @Override
    protected String getPathAndParams() {
        return "moment/get?username="+ UserInfoManager.getInstance().getUser().getUsername() +"&page="+pageIndex.value;
    }

    @Override
    protected void handleResult(String result) {
        try {
            List<CircleEntity> circleEntities=new ArrayList<>();
            JSONObject jsonObject=new JSONObject(result);
            int code=jsonObject.getInt("code");
            if(code!=200){
                return;
            }
            JSONArray data=jsonObject.getJSONArray("data");
            int len=data.length();
            if(len==0){
                return;
            }
            pageIndex.value++;
            for (int i=0;i<len;i++){
                JSONObject item=data.getJSONObject(i);
                CircleEntity entity=new CircleEntity()
                        .setId(item.getInt("id"))
                        .setTitle(item.getString("content"))
                        .setLikeCount((String.valueOf(item.getInt("like"))))
                        .setPictureSrc(DOMAIN_HOST+IMAGES+item.getString("coverPath"))
                        .setSenderName(item.getString("nickname"))
                        .setSenderHeaderPictureSrc(DOMAIN_HOST+IMAGES+ item.getString("userHeadPath"))
                        .setLiked(item.getBoolean("liked"))
                        .setSendTime(item.getString("postTime"));
                circleEntities.add(entity);
            }
            setHandleResultRunnable(new Runnable() {
                @Override
                public void run() {
                    if(pageIndex.value==1){
                        removeAllItem();
                    }
                    for(CircleEntity entity:circleEntities){
                        addItem(entity);
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
}
